package com.tulele.vtool.handler;

import com.google.common.collect.Maps;
import com.tulele.vtool.model.ArticleInfo;
import com.tulele.vtool.model.ArticleTailAdvertInfo;
import com.tulele.vtool.model.ArticleTypeInfo;
import com.tulele.vtool.model.combinedEntity.CombinedArticleTailAdvertInfo;
import com.tulele.vtool.model.combinedEntity.CombinedArticleTypeAdvertTemplate;
import com.tulele.vtool.model.combinedEntity.UserAdvertList;
import com.tulele.vtool.model.reqEntity.UserAdvertReqBean;
import com.tulele.vtool.model.combinedEntity.UserAdvertType;
import com.tulele.vtool.model.reqEntity.UserArticleAdvertReqBean;
import com.tulele.vtool.model.respEntity.RespData;
import com.tulele.vtool.model.respEntity.ReturnCode;
import com.tulele.vtool.service.ArticleTailAdvertInfoService;
import com.tulele.vtool.service.IArticleInfoService;
import com.tulele.vtool.service.IArticleTypeInfoService;
import com.tulele.vtool.service.IUserRelateArticleTypeInfoService;
import com.tulele.vtool.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@Slf4j
@RestController
public class ArticleTailAdvertInfoHandler {
    @Autowired
    private ArticleTailAdvertInfoService articleTailAdvertInfoService;

    @Autowired
    private IArticleInfoService articleInfoService;

    @Autowired
    private IArticleTypeInfoService articleTypeInfoService;

    @Autowired
    private IUserRelateArticleTypeInfoService userRelateArticleTypeInfoService;

    /**
     * 获取用户的广告列表
     * @param userId 用户编号
     * @param advertType 广告类型(其中 -1 表示全部)
     * @return 用户的广告列表
     */
    @GetMapping(value = "/getArticleTailAdvertInfo", produces = "application/json;charset=UTF-8")
    public RespData getArticleTailAdvertInfo(@RequestHeader("userId") String userId, @RequestParam Integer advertType) {
        List<UserAdvertList> articleAdvertList = articleTailAdvertInfoService.getArticleTailAdvertInfo(Integer.parseInt(userId), advertType);
//        log.info("[articleAdvertList] = " + articleAdvertList);

        HashMap<String, Object> resultMap = Maps.newHashMapWithExpectedSize(1);
        resultMap.put("articleAdvertList", articleAdvertList);

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("OK");
        respData.setData(resultMap);
//        System.out.println("[resultMap] =" + resultMap);
//        log.info("[resultMap] =" + resultMap);

        return respData;
    }

    /**
     * 保存用户的广告信息
     * @param userId 用户编号
     * @param articleTailAdvertInfo 广告实体
     * @return 用户广告编号
     */
    @PostMapping(value = "/saveUserAdvert", produces = "application/json;charset=UTF-8")
    public RespData saveUserAdvert(@RequestHeader("userId") String userId, @RequestBody ArticleTailAdvertInfo articleTailAdvertInfo) {
        if (Objects.isNull(articleTailAdvertInfo) || StringUtils.isBlank(articleTailAdvertInfo.getAdvertName())
            || Objects.isNull(articleTailAdvertInfo.getArticleTypeId()) || StringUtils.isBlank(articleTailAdvertInfo.getAdvertContent())) {
            RespData respData = new RespData();
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数异常");
            return respData;
        }

        Integer id = articleTailAdvertInfo.getId();
        HashMap<String, Object> resultMap = Maps.newHashMapWithExpectedSize(1);
        if (Objects.isNull(id)) {// 如果 id 为空，则新增
            ArticleTailAdvertInfo info = new ArticleTailAdvertInfo();
            info.setAdvertName(articleTailAdvertInfo.getAdvertName());
            info.setUserId(Integer.parseInt(userId));
            info.setArticleTypeId(articleTailAdvertInfo.getArticleTypeId());
            info.setAdvertContent(articleTailAdvertInfo.getAdvertContent());
            info.setAdvertStatus(Integer.valueOf(1));

            Date curDate = DateUtil.getCurDate();
            info.setCreateTime(curDate);
            info.setModifyTime(curDate);

            articleTailAdvertInfoService.saveArticleTailAdvert(info);
            resultMap.put("advertId", info.getId());
        } else {// 如果 ID 不为空,则修改
            articleTailAdvertInfo.setModifyTime(DateUtil.getCurDate());
            articleTailAdvertInfoService.updateArticleTailAdvert(articleTailAdvertInfo);
            resultMap.put("advertId", id);
        }

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("OK");
        respData.setData(resultMap);

        return respData;
    }

    /**
     * 修改广告
     * @param articleTailAdvertInfo 广告实体
     * @return
     */
    /*@PostMapping(value = "/updateUserAdvert", produces = "application/json;charset=UTF-8")
    public RespData updateUserAdvert(@RequestBody ArticleTailAdvertInfo articleTailAdvertInfo) {
        if (Objects.isNull(articleTailAdvertInfo) || Objects.isNull(articleTailAdvertInfo.getId())) {
            RespData respData = new RespData();
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数异常");
            return respData;
        }

        articleTailAdvertInfo.setModifyTime(DateUtil.getCurDate());
        articleTailAdvertInfoService.updateArticleTailAdvert(articleTailAdvertInfo);

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("OK");

        return respData;
    }*/

    /**
     * 删除广告
     * @param userAdvertReqBean
     * @return
     */
    @PostMapping(value = "/deleteUserAdvert", produces = "application/json;charset=UTF-8")
    public RespData deleteUserAdvert(@RequestBody UserAdvertReqBean userAdvertReqBean) {
        if (Objects.isNull(userAdvertReqBean) || Objects.isNull(userAdvertReqBean.getAdvertId())) {
            RespData respData = new RespData();
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数异常");
            return respData;
        }

        articleTailAdvertInfoService.deleteArticleTailAdvert(userAdvertReqBean.getAdvertId());

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("OK");

        return respData;
    }

    /**
     * 根据文章编号获取用户的广告
     * @param userId 用户编号
     * @param userArticleAdvertReqBean 文章ID
     * @return 广告信息
     */
    @PostMapping(value = "/getUserAdvertByArticleId", produces = "application/json;charset=UTF-8")
    public RespData getUserAdvertByArticleId(@RequestHeader("userId") String userId, @RequestBody UserArticleAdvertReqBean userArticleAdvertReqBean) {
        if (Objects.isNull(userArticleAdvertReqBean) || Objects.isNull(userArticleAdvertReqBean.getArticleId())) {
            RespData respData = new RespData();
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数异常");
            return respData;
        }

        HashMap<String, Object> resultMap = Maps.newHashMapWithExpectedSize(1);

        // 根据文章 ID 获取文章的类型
        ArticleInfo articleInfo = articleInfoService.getArticleDetailInfo(userArticleAdvertReqBean.getArticleId());
        Integer articleTypeId = articleInfo.getArticleTypeId();

        String articleTypeName = articleTypeInfoService.getTypeInfoByTypeId(articleTypeId);// 根据类型编号获取类型名称

        // 获取用户该类型的广告
        ArticleTailAdvertInfo articleTailAdvertInfo = articleTailAdvertInfoService.getAdvertByType(Integer.parseInt(userId), articleTypeId);

        CombinedArticleTailAdvertInfo resultInfo = new CombinedArticleTailAdvertInfo();
        if (Objects.isNull(articleTailAdvertInfo)) {
            // 使用默认方案
            resultInfo.setArticleTypeId(articleTypeId);
            resultInfo.setAdvertContent(articleTypeInfoService.getDefaultAdvertInfo(articleTypeId));
        } else {
            resultInfo.setId(articleTailAdvertInfo.getId());
            resultInfo.setAdvertName(articleTailAdvertInfo.getAdvertName());
            resultInfo.setArticleTypeId(articleTailAdvertInfo.getArticleTypeId());
            resultInfo.setAdvertContent(articleTailAdvertInfo.getAdvertContent());
        }
        resultInfo.setArticleTypeName(articleTypeName);

        resultMap.put("articleTailAdvertInfo", resultInfo);

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("OK");
        respData.setData(resultMap);

        return respData;
    }

    /**
     * 获取用户广告的类型
     * @param userId 用户编号
     * @return 用户广告的类型列表
     */
    @GetMapping(value = "/getUserAdertType", produces = "application/json;charset=UTF-8")
    public RespData getUserAdertType(@RequestHeader("userId") String userId) {
        // 获取用户关注的类型
        String articleTypeIds = userRelateArticleTypeInfoService.getUserRelateArticleTypeInfo(Integer.parseInt(userId)).getArticleTypeIds();

        // 通过遍历
        String[] articleTypeIdArray = articleTypeIds.split(",");
        List<Integer> articleTypeIdList = new ArrayList<Integer>();
        for (String articleTypeIdString : articleTypeIdArray) {
            Integer articleTypeId = null;

            // 先对 articleTypeIdString 判空
            if(StringUtils.isNotBlank(articleTypeIdString) && StringUtils.isNumeric(articleTypeIdString)){
                articleTypeId = Integer.valueOf(articleTypeIdString);
                articleTypeIdList.add(articleTypeId);
            }
        }

        List<UserAdvertType> userAdvertList = articleTailAdvertInfoService.getAdvertTypeList(Integer.parseInt(userId), articleTypeIdList);

        HashMap<String, Object> resultMap = Maps.newHashMapWithExpectedSize(1);
        resultMap.put("userAdvertList", userAdvertList);

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("OK");
        respData.setData(resultMap);

        return respData;
    }

    /**
     * 根据广告 ID 获取广告信息
     * @param id 广告 ID
     * @return 广告信息
     */
    @GetMapping(value = "/getUserAdvertById", produces = "application/json;charset=UTF-8")
    public RespData getUserAdvertById(@RequestParam Integer id) {
        ArticleTailAdvertInfo advertInfo = articleTailAdvertInfoService.getUserAdvertById(id);

        String articleTypeName = articleTypeInfoService.getTypeInfoByTypeId(advertInfo.getArticleTypeId());// 根据类型编号获取类型名称

        CombinedArticleTailAdvertInfo resultInfo = new CombinedArticleTailAdvertInfo();
        resultInfo.setId(advertInfo.getId());
        resultInfo.setAdvertName(advertInfo.getAdvertName());
        resultInfo.setAdvertContent(advertInfo.getAdvertContent());
        resultInfo.setArticleTypeId(advertInfo.getArticleTypeId());
        resultInfo.setArticleTypeName(articleTypeName);

        HashMap<String, Object> resultMap = Maps.newHashMapWithExpectedSize(1);
        resultMap.put("advertInfo", resultInfo);

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("OK");
        respData.setData(resultMap);

        return respData;
    }

    /**
     * 获取用户订阅的文章类型的模板广告
     * @param userId 用户 ID
     * @return 用户订阅的文章类型的模板广告
     */
    @GetMapping(value = "/advert/template", produces = "application/json;charset=UTF-8")
    public RespData getUserAdvertTemplate(@RequestHeader("userId") String userId) {
        // 获取用户关注的类型
        String articleTypeIds = userRelateArticleTypeInfoService.getUserRelateArticleTypeInfo(Integer.parseInt(userId)).getArticleTypeIds();

        // 通过遍历
        String[] articleTypeIdArray = articleTypeIds.split(",");
        List<Integer> articleTypeIdList = new ArrayList<Integer>();
        for (String articleTypeIdString : articleTypeIdArray) {
            Integer articleTypeId = null;

            // 先对 articleTypeIdString 判空
            if(StringUtils.isNotBlank(articleTypeIdString) && StringUtils.isNumeric(articleTypeIdString)){
                articleTypeId = Integer.valueOf(articleTypeIdString);
                articleTypeIdList.add(articleTypeId);
            }
        }

        // 用户已经创建的广告类型
        List<Integer> userAdvertTypeList = articleTailAdvertInfoService.getUserAdvertTypeList(Integer.valueOf(userId));

        if (!CollectionUtils.isEmpty(userAdvertTypeList)) {
            articleTypeIdList.removeAll(userAdvertTypeList);// 除去已经有的

            // 如果用户创建了默认广告，则不再显示
            if (!userAdvertTypeList.contains(-1)) {
                articleTypeIdList.add(-1);
            }
        } else {
            articleTypeIdList.add(-1);
        }

        // 根据类型获取广告模板
        List<CombinedArticleTypeAdvertTemplate> articleTypeAdvertTemplateList = articleTypeInfoService.getArticleTypeAdvertTemplate(articleTypeIdList);

        HashMap<String, Object> resultMap = Maps.newHashMapWithExpectedSize(1);
        resultMap.put("articleTypeAdvertTemplateList", articleTypeAdvertTemplateList);

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("OK");
        respData.setData(resultMap);

        return respData;
    }

    /**
     * 根据文章类型 ID 获取广告模板信息
     * @param articleTypeId 类型 ID
     * @return
     */
    @GetMapping(value = "/advert/typetemplate")
    public RespData getTemplateAdvertByArticleTypeId(@RequestParam Integer articleTypeId) {
        ArticleTypeInfo articleTypeInfo = articleTypeInfoService.getInfoById(articleTypeId);

        HashMap<String, Object> resultMap = Maps.newHashMapWithExpectedSize(3);
        resultMap.put("articleTypeId", articleTypeInfo.getId());
        resultMap.put("articleTypeName", articleTypeInfo.getArticleTypeName());
        resultMap.put("advertContent", articleTypeInfo.getArticleTemplateContent());

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("OK");
        respData.setData(resultMap);

        return respData;
    }


}
